package yrjdezu.abab.engineerpractice2.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import yrjdezu.abab.engineerpractice2.common.properties.JwtProperties;
import yrjdezu.abab.engineerpractice2.common.result.Result;
import yrjdezu.abab.engineerpractice2.common.util.JwtUtil;
import yrjdezu.abab.engineerpractice2.domain.dto.UserDTO;
import yrjdezu.abab.engineerpractice2.domain.entity.Users;
import yrjdezu.abab.engineerpractice2.service.IUsersService;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lzh
 * @since 2025-05-18
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理接口")
@Slf4j
public class UsersController {

    @Autowired
    private IUsersService usersService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@RequestBody UserDTO userDTO) {
        log.info("用户登录请求：identifier={}, password长度={}", userDTO.getUsername(), 
                 userDTO.getPassword() != null ? userDTO.getPassword().length() : 0);

        try {
            Users users = usersService.login(userDTO);
            
            // 检查用户是否存在
            if (users == null) {
                log.warn("登录失败：用户名/邮箱或密码错误 - {}", userDTO.getUsername());
                return Result.error("用户名/邮箱或密码错误");
            }
            
            log.info("登录成功：用户ID={}, 用户名={}, 邮箱={}", users.getId(), users.getUsername(), users.getEmail());
            
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", users.getId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getSecretKey(),
                    jwtProperties.getTtl(),
                    claims);
                    
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("userId", users.getId());
            responseData.put("token", token);

            return Result.success(responseData);
        } catch (Exception e) {
            log.error("登录过程发生异常：", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserDTO userDTO) {
        log.info("用户注册：{}", userDTO);
        
        try {
            // 注册用户
            Users users = usersService.register(userDTO);
            if (users == null) {
                return Result.error("用户名已存在，请更换用户名");
            } else if (users.getId() != null && users.getId() == -1) {
                return Result.error("邮箱已被注册，请更换邮箱或找回密码");
            }
            
            return Result.success("注册成功");
        } catch (Exception e) {
            log.error("注册失败：", e);
            return Result.error("注册失败：" + e.getMessage());
        }
    }
}
